package dahuiji.findPassword.servlet;

import java.io.IOException;


import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import dahuiji.common.entity.User;
import dahuiji.common.servlet.BaceServlet;
import dahuiji.common.util.Constants;
import dahuiji.common.util.SendMail;
import dahuiji.findPassword.service.FindPasswordService;

public class FindPassword extends BaceServlet {

	/**
	 * Constructor of the object.
	 */
	public FindPassword() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

	@Override
	public String perform(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String result = null;
		String nextPage = null;// 跳转页面
		HttpSession session = request.getSession();
		String code = (String) session.getAttribute("verifycode");
		RequestDispatcher rd;
		String email = request.getParameter("email");
		String codeInput = request.getParameter("vf");
		FindPasswordService findPassword=null;
		User user=(User) session.getAttribute("user");
		if (email == null || codeInput.equals("")) {
			result = "请输入邮箱";
		} else if (codeInput == null || codeInput.equals("")) {
			result = "请输入验证码";
		}else{
			findPassword=new FindPasswordService();
			String emailString=findPassword.getUserByEamil(email);
			if(emailString==null){
				result = "此邮箱没有注册过";
			}
			else{
				String newPassword=findPassword.productPassword();//得到新密码
				SendMail sendMail = new SendMail();
				sendMail.send(Constants.STMP, Constants.MY_EMAIL,
						Constants.MY_EMAIL_P, emailString, Constants.FIND_P_SUB,
						Constants.FIND_P_MSG + newPassword + "");//发送邮箱通知
				findPassword.updatePassword(newPassword, user.getId());
				result = "新密码已经发送到你的邮箱里！";

			}
		}
		nextPage = "/view/findpassword/findPassword.jsp";
		request.setAttribute("msg", result);
		rd = getServletContext().getRequestDispatcher(nextPage);
		rd.forward(request, response);

		return null;
	}

}
